package com.cimr.controller.user;

import com.cimr.comm.bo.MenuBo;
import com.cimr.comm.dto.HttpResult;
import com.cimr.comm.dto.LayuiTableData;
import com.cimr.comm.po.Group;
import com.cimr.comm.po.Role;
import com.cimr.comm.po.User;
import com.cimr.comm.service.GroupService;
import com.cimr.comm.service.MenuService;
import com.cimr.comm.service.RoleService;
import com.cimr.comm.service.UserService;
import com.cimr.comm.token.TokenUtil;
import com.cimr.comm.util.IdUtil;
import com.cimr.dto.ZtreeDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zengfan on 2017/12/29.
 */
@Controller
@RequestMapping("/role/ajax")
public class RoleManagmentAjaxController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private GroupService groupService;
    @RequestMapping({"getRoleById"})
    @ResponseBody
    public HttpResult getRoleById( String id) {
        HttpResult result = new HttpResult(true, "");
        Role role = roleService.getRoleById(id);
        result.setData(role);
        return result;
    }
    /**
    *@auther zengfan
    *@date 2018/1/4 10:01
    *@params  * @param null
    *弹出菜单授权表单页需先查询当前角色已授权，然后组装成树形数据
    **/
    @RequestMapping({"getMenuZtree"})
    @ResponseBody
    public HttpResult getMenuPer(String id) {
        HttpResult result = new HttpResult(true, "");
        List<MenuBo> allMenuList = menuService.getMenuList();
        List<MenuBo> curMenuList = menuService.getMenuListByRoleId(id);
        List<ZtreeDto> ztreeList = new ArrayList<ZtreeDto>();

        for (int i = 0;i<allMenuList.size();i++){
            ZtreeDto ztreeDto = new ZtreeDto();
            ztreeDto.setId(allMenuList.get(i).getId());
            ztreeDto.setpId(allMenuList.get(i).getParentId());
            if (allMenuList.get(i).getLevel()==1){
                ztreeDto.setParent(true);
            }
            if (allMenuList.get(i).getLevel()==2){
                ztreeDto.setParent(false);
            }
            ztreeDto.setName(allMenuList.get(i).getMenuName());
            ztreeDto.setChecked(false);
            for (int j=0;j<curMenuList.size();j++){
                if (allMenuList.get(i).getId().equals(curMenuList.get(j).getId())){
                    ztreeDto.setChecked(true);
                    break;
                };
            }
            ztreeList.add(ztreeDto);
        }
        result.setData(ztreeList);
        return result;
    }
    /**
     *@auther zengfan
     *@date 2018/1/4 14:28
     *@params  * @param null
     *保存菜单配置
     **/
    @RequestMapping({"saveMenuPer"})
    @ResponseBody
    public HttpResult saveMenuPer(String id, String menuIds) {
        int resultStatus1;
        String s = menuIds.substring(1, menuIds.length()-1);
        String[] menuIdsArray=s.split(",");
        for (int i = 0 ;i<menuIdsArray.length;i++){
            menuIdsArray[i]=menuIdsArray[i].substring(1, menuIdsArray[i].length()-1);
        }
        resultStatus1 = roleService.saveRoleAndMenus(id,menuIdsArray);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }
        return result;
    }
    /**
     *@auther zengfan
     *@date 2018/1/4 14:28
     *@params  * @param null
     *保存操作配置
     **/
    @RequestMapping({"saveOpationPer"})
    @ResponseBody
    public HttpResult saveOpationPer(String id, String ids) {
        String[] idArray = ids.split(",");
        int resultStatus1;
        resultStatus1 = roleService.saveRoleAndOperations(id,idArray);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }
        return result;
    }
    /**
     *@auther zengfan
     *@date 2018/1/4 14:28
     *@params  * @param null
     *保存角色配置
     **/
    @RequestMapping({"saveRolePer"})
    @ResponseBody
    public HttpResult saveRolePer(String id, String ids) {
        int resultStatus1;
        HttpResult result = new HttpResult(true, "");
        if(ids==""||ids==null){
            resultStatus1 = userService.saveUserAndRoles(id,null);
        }else{
            String[] idArray = ids.split(",");
            List<String> idList= new ArrayList<>();
            for(int i=0;i<idArray.length;i++){
                if (idArray[i]!=null){
                    idList.add(idArray[i]);
                }
            }
            String[] roleArray = new String[idList.size()];
            for (int i=0;i<idList.size();i++){
                roleArray[i] = idList.get(i);
            }
            resultStatus1 = userService.saveUserAndRoles(id,roleArray);
            if(resultStatus1 == 0) {
                result.setSuccess(false);
            }
        }
        return result;
    }
    @RequestMapping({"/getRoleManagerList"})
    @ResponseBody
    public LayuiTableData getRoleManagerList(@RequestParam(required = true,defaultValue = "1") Integer page, @RequestParam(required = false,defaultValue = "10") Integer limit, @RequestParam(required = false) String roleName) {

        LayuiTableData result = new LayuiTableData();
        User currentUser = TokenUtil.getToken();
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(currentUser.getGroupId());
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            PageHelper.startPage(page, limit);
            List list = roleService.getRoleListWithName(roleName, groupIds);
            if (list!=null && list.size()>0) {
                PageInfo pageInfo = new PageInfo(list);
                List list1 = roleService.getRoleListWithName(roleName, groupIds);
                result.setCount(list1.size());
                result.setData(pageInfo.getList());
            }
        }
        result.setCode(Integer.valueOf(0));
        result.setMsg("");
        return result;
    }

    @RequestMapping({"getRolesByUserId"})
    @ResponseBody
    public HttpResult getRolesByUserId(@RequestParam(required = true) String id) {
        List<Role> currentList = roleService.getRoleListByUserId(id);
        HttpResult result = new HttpResult(true, "");
        result.setData(currentList);
        return result;
    }
    @RequestMapping({"saveRole"})
    @ResponseBody
    public HttpResult saveRole(String id,String roleKey,String roleName,String comment,Float orderId) {
        int resultStatus1;
        if(id != null && !"".equals(id)) {
            resultStatus1 = this.roleService.updateRole(id, roleKey, roleName, comment, orderId, null, null);
        } else {
            resultStatus1 = this.roleService.insertRole(IdUtil.getId().toString(), roleKey, roleName, comment, orderId, null, null);
        }

        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }

        return result;
    }

    @RequestMapping({"deleteRole"})
    @ResponseBody
    public HttpResult deleteRole(@RequestParam(required = true) String id) {
        int resultStatus = roleService.deleteRoleById(id);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus == 0) {
            result.setSuccess(false);
        }
        return result;
    }
    @RequestMapping({"getRoleListByKey"})
    @ResponseBody
    public HttpResult getRoleListByKey(@RequestParam(required = true) String roleKey) {
        List<Role> roleList = roleService.getRoleListByKey(roleKey);
        HttpResult result = new HttpResult(true, "");
       if(roleList!=null){
           if(roleList.size()==0){
               result.setData(null);
           }else{
               result.setData(roleList);
           }
       }
        return result;
    }
}
